package com.chpro.common;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import org.apache.commons.io.IOUtils;

/**
 * Created by Administrator on 14-8-30.
 */
public class NetworkUtil {

    /**
     * 获取操作系统类型
     *
     * @return 返回操作系统类型<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
    </dependency>
     */
    public static String getOsName() {
        return System.getProperty("os.name");
    }

    /**
     * 通过运行命令获取本机mac地址(支持window和linux平台)
     *
     * @return 返回mac地址
     */
    public static String getMACAddress() {
        String address = "";
        String os = getOsName();
        if (null != os) {
            if (os.startsWith("Windows")) {
                address = getWindowsMACAddres();
            } else if (os.startsWith("Linux")) {
                address = getLinuxAddres();
            }
        }
        return address;
    }

    /***
     * 获取window平台下面的MAC地址
     *
     * @return
     */
    public static String getWindowsMACAddres() {
        String address = "";
        BufferedReader br = null;
        try {
            String command = "cmd.exe /c ipconfig /all";
            Process p = Runtime.getRuntime().exec(command);
            br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                if (line.indexOf("Physical Address") > 0) {
                    int index = line.indexOf(':');
                    index += 2;
                    address = line.substring(index);
                    break;
                }
            }
        } catch (Exception e) {

        } finally {
            IOUtils.closeQuietly(br);
        }
        return address.trim();
    }

    /***
     * 获取Linux平台下面MAC地址
     *
     * @return
     */
    public static String getLinuxAddres() {
        String address = "";
        BufferedReader br = null;
        String command = "/bin/sh -c ifconfig -a";
        try {
            Process p = Runtime.getRuntime().exec(command);
            br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                if (line.indexOf("HWaddr") > 0) {
                    int index = line.indexOf("HWaddr") + "HWaddr".length();
                    address = line.substring(index);
                    break;
                }
            }
        } catch (IOException e) {

        } finally {
            IOUtils.closeQuietly(br);
        }
        return address.trim();
    }

    /**
     * 根据ip地址获取mac地址
     *
     * @param ipAddress
     *            ip地址
     * @return 返回mac地址
     */
    public static String getMACAddress(String ipAddress) {
        String str = "";
        String mac = "";
        InputStreamReader ir = null;
        LineNumberReader input = null;
        try {
            Process pp = Runtime.getRuntime().exec("nbtstat -a " + ipAddress);
            ir = new InputStreamReader(pp.getInputStream());
            input = new LineNumberReader(ir);
            for (int i = 1; i < 100; i++) {
                str = input.readLine();
                if (str != null) {
                    if (str.indexOf('=') > 1) {
                        mac = str.substring(str.indexOf('=') + 1);
                        break;
                    }
                }
            }
        } catch (IOException ex) {
            return "Can't Get MAC Address!";
        } finally {
            IOUtils.closeQuietly(ir);
            IOUtils.closeQuietly(input);
        }
        if (mac.length() < 17) {
            return "";
        }
        return mac;
    }

    /**
     * 获取请求ip地址
     *
     * @param request
     *            请求对象
     * @return 返回发送请求的ip地址
     */
    public static String getIpAddrByRequest( HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 获取本机真实ip地址
     *
     * @return 返回本机真实IP
     */
    public static String getRealIp() {
        // 本地IP，如果没有配置外网IP则返回它
        String localip = null;
        // 外网IP
        String netip = null;
        try {
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface
                    .getNetworkInterfaces();
            InetAddress ip = null;
            // 是否找到外网IP
            boolean finded = false;
            while (netInterfaces.hasMoreElements() && !finded) {
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> address = ni.getInetAddresses();
                while (address.hasMoreElements()) {
                    ip = address.nextElement();
                    // 外网IP
                    if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
                            && ip.getHostAddress().indexOf(':') == -1) {
                        netip = ip.getHostAddress();
                        finded = true;
                        break;
                    } else if (ip.isSiteLocalAddress()
                            && !ip.isLoopbackAddress()
                            && ip.getHostAddress().indexOf(':') == -1) {
                        // 内网IP
                        localip = ip.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
        }
        if (netip != null && !"".equals(netip)) {
            return netip;
        } else {
            return localip;
        }

    }
}
